//
//  PhotoFilterViewController.m
//  VideoDemo
//
//  Created by wangxue on 16/9/19.
//  Copyright © 2016年 dfl. All rights reserved.
//

#import "PhotoFilterViewController.h"
#import "Constants.h"

@interface PhotoFilterViewController ()
//相片照相机
@property (nonatomic) GPUImageStillCamera *stillCamera;
//滤镜
@property (nonatomic) GPUImageOutput<GPUImageInput> *filter;

//
@property (nonatomic) GPUImageView *filterView;


@property (nonatomic) UIButton *photoCaptureButton;

@property (nonatomic) NSString *appName;

@property (nonatomic) UIButton *cancelBtn;

@property (nonatomic) UIButton *flashBtn;


@property (nonatomic) BOOL isFont;

@property (nonatomic) BOOL openFlash;



//改变摄像头
@property (nonatomic) UIButton *cameraBtn;



@end

@implementation PhotoFilterViewController

#pragma mark - 生命周期


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.appName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"];
    if (!self.appName) self.appName = [[NSBundle mainBundle].infoDictionary valueForKey:@"CFBundleName"];

    
    if ([self allIsEmpty:self.albumName])
    {
        self.albumName = self.appName;
    }
    
    if (![self PhotosjudgeIsHaveCameraAuthority]) {
        self.view.backgroundColor = [UIColor whiteColor];
        UIButton *warningLabe = [UIButton buttonWithType:UIButtonTypeCustom];
        warningLabe.titleLabel.numberOfLines = 0;
        [warningLabe setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [warningLabe setTitle:[NSString stringWithFormat:@"请在iPhone的设置-隐私->允许%@访问你的相机",self.appName] forState:UIControlStateNormal];
        warningLabe.frame = self.view.frame;
        [self.view addSubview:warningLabe];
        [warningLabe addTarget:self action:@selector(setingBtn:) forControlEvents:UIControlEventTouchUpInside];
       
    }else {
    
    _filterView = [GPUImageView new];
    _filterView.fillMode = kGPUImageFillModePreserveAspectRatioAndFill;
    _filterView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
   
    [self.view addSubview:_filterView];
    [_filterView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(60);
        make.bottom.equalTo(-100);
        make.left.right.equalTo(0);

    }];
    
    self.view.backgroundColor = [UIColor colorWithRed:38/255.0 green:38/255.0 blue:38/255.0 alpha:1];
;
    
    [self.stillCamera addTarget:self.filter];
    [self.filter addTarget:_filterView];
    [self.stillCamera startCameraCapture];
    
    [self photoCaptureButton];
    [self cancelBtn];
    [self cameraBtn];
    
    [self.view addSubview:self.flashBtn];
        
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone){
    [_flashBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.cancelBtn.mas_right).equalTo(20);
            make.bottom.equalTo(self.cancelBtn.mas_bottom).equalTo(-5);
            make.size.equalTo(CGSizeMake(30, 30));
    }];
        }

    
    self.isFont = YES;
    self.openFlash = YES;
    }
}

- (void)setingBtn:sender {
   
    if (IOS_VERSION_8_OR_ABOVE) {
        
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        } else {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=Privacy&path=CAMERA"]];
        }
        
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
   }

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated ];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation

{
    // Map UIDeviceOrientation to UIInterfaceOrientation.
    UIInterfaceOrientation orient = UIInterfaceOrientationPortrait;
    switch ([[UIDevice currentDevice] orientation])
    {
        case UIDeviceOrientationLandscapeLeft:
            orient = UIInterfaceOrientationLandscapeLeft;
            break;
            
        case UIDeviceOrientationLandscapeRight:
            orient = UIInterfaceOrientationLandscapeRight;
            
            break;
            
        case UIDeviceOrientationPortrait:
            orient = UIInterfaceOrientationPortrait;

            break;
            
        case UIDeviceOrientationPortraitUpsideDown:
            orient = UIInterfaceOrientationPortraitUpsideDown;
            break;
            
        case UIDeviceOrientationFaceUp:
        case UIDeviceOrientationFaceDown:
        case UIDeviceOrientationUnknown:
            // When in doubt, stay the same.
            orient = fromInterfaceOrientation;
            break;
    }
    self.stillCamera.outputImageOrientation = orient;
    }

- (UIStatusBarStyle)preferredStatusBarStyle {
    
    return UIStatusBarStyleLightContent;
}




#pragma mark - 方法

- (void)takePhoto:(UIButton *)sender {
    
    if (![self PhotosjudgeIsHavePhotoAblumAuthority] ){
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"请在iPhone的设置-隐私->允许%@访问你的照片",self.appName] preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            if (IOS_VERSION_8_OR_ABOVE) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
            } else {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=Privacy&path=PHOTOS"]];
            }
            
        }];
        [alertController addAction:sureAction];
        [self presentViewController:alertController animated:YES completion:nil];
        
        return;
    }

    [self.photoCaptureButton setEnabled:NO];
    [self.stillCamera capturePhotoAsJPEGProcessedUpToFilter:self.filter withCompletionHandler:^(NSData *processedJPEG, NSError *error) {
        
       
        ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
        UIImage *image = [UIImage imageWithData:processedJPEG];
        [library saveImage:image toAlbum:self.albumName completion:^(NSURL *assetURL, NSError *error) {
            
            dispatch_main_async_safe(^{
                self.photoCaptureButton.enabled = YES;
                });
            if (self.completBlock){
                
                self.completBlock(assetURL,image);
            }
            [self dismissViewControllerAnimated:YES completion:nil];
        } failure:^(NSError *error) {
            if (error)
            {
                NSLog(@"%@",error);
            }
        }];
           }];
    
}

- (void)cancelPhoto {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (void)changeCamera:(UIButton *)sender {

    [self.stillCamera stopCameraCapture];
    self.stillCamera = nil;
    if (self.isFont){
        self.stillCamera = [[GPUImageStillCamera alloc] initWithSessionPreset:AVCaptureSessionPreset640x480 cameraPosition:AVCaptureDevicePositionFront];
        self.stillCamera.horizontallyMirrorFrontFacingCamera = YES;
        self.stillCamera.outputImageOrientation = UIInterfaceOrientationPortrait;
        [self.stillCamera addTarget:self.filter];
        [self.filter addTarget:_filterView];
        self.flashBtn.hidden = YES;
       

    }else{
        self.stillCamera = [[GPUImageStillCamera alloc] initWithSessionPreset:AVCaptureSessionPreset640x480 cameraPosition:AVCaptureDevicePositionBack];
        self.stillCamera.horizontallyMirrorFrontFacingCamera = YES;
        self.stillCamera.outputImageOrientation = UIInterfaceOrientationPortrait;
        [self.stillCamera addTarget:self.filter];
        [self.filter addTarget:_filterView];
         self.flashBtn.hidden = NO;



    }
    [self.stillCamera startCameraCapture];

    self.isFont = !self.isFont;
    
   
}

- (void)changeFlashModel:(UIButton *)sender
{
    sender.selected = !sender.selected;
    
    if (self.openFlash)
        
    {
        [self.stillCamera.inputCamera lockForConfiguration:nil];
        [self.stillCamera.inputCamera setFlashMode:AVCaptureFlashModeOn];
        [self.stillCamera.inputCamera unlockForConfiguration];
        
    }else{
        
        [self.stillCamera.inputCamera lockForConfiguration:nil];
        [self.stillCamera.inputCamera setFlashMode:AVCaptureFlashModeOff];
        [self.stillCamera.inputCamera unlockForConfiguration];
    }
    
    self.openFlash = !self.openFlash;

}

#pragma mark - 使用权限
//相册使用权限
- (BOOL)PhotosjudgeIsHavePhotoAblumAuthority {
    
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    ALAuthorizationStatus state = [ALAssetsLibrary authorizationStatus];
    // 家长控制,不允许访问
    if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) {
        return NO;
    }else if (state == ALAuthorizationStatusRestricted || state == ALAuthorizationStatusDenied) {
        return NO;
    }
    return YES;
}
//相机使用权限
- (BOOL)PhotosjudgeIsHaveCameraAuthority
{
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (status == AVAuthorizationStatusRestricted ||
        status == AVAuthorizationStatusDenied) {
        return NO;
    }
    return YES;
}


#pragma mark - 懒加载
//照相机
- (GPUImageStillCamera *)stillCamera {
    
    if(!_stillCamera) {
        
        //_stillCamera = [[GPUImageStillCamera alloc] init];
        _stillCamera  =[[GPUImageStillCamera alloc] initWithSessionPreset:AVCaptureSessionPreset640x480 cameraPosition:AVCaptureDevicePositionBack];
        //_stillCamera.horizontallyMirrorRearFacingCamera = YES;
        _stillCamera.horizontallyMirrorFrontFacingCamera = YES;
        _stillCamera.outputImageOrientation = UIInterfaceOrientationPortrait;
        
        if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone){
        [_stillCamera.inputCamera lockForConfiguration:nil];
        [_stillCamera.inputCamera setFlashMode:AVCaptureFlashModeOff];
        [_stillCamera.inputCamera unlockForConfiguration];
        }

    }
    
    return _stillCamera;
}

- (UIButton *)photoCaptureButton {
    
    if (!_photoCaptureButton)
    {
        _photoCaptureButton = [UIButton buttonWithType:UIButtonTypeCustom];
       
        NSString *imagePathInControllerBundlePlay = [NSString stringWithFormat:@"YuanXinCamera.bundle/%@", @"play"];
       

        [_photoCaptureButton setImage:[UIImage imageNamed:imagePathInControllerBundlePlay] forState:UIControlStateNormal];
        _photoCaptureButton.layer.borderColor = [UIColor whiteColor].CGColor;
        _photoCaptureButton.layer.borderWidth = 1.0;
        _photoCaptureButton.layer.cornerRadius = 40;
        [self.view addSubview:_photoCaptureButton];
        [_photoCaptureButton mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.equalTo(0);
                make.size.equalTo(CGSizeMake(80, 80));
                make.bottom.equalTo(-10);
            }];
        [_photoCaptureButton addTarget:self action:@selector(takePhoto:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _photoCaptureButton;
    
}

- (GPUImageOutput<GPUImageInput> *)filter

{
    if (!_filter)
    {
        // GPUImageBeautifyFilter 美颜滤镜
        _filter = [[GPUImageFilter alloc]init];
        
    }
    return _filter;
}

- (UIButton *)cancelBtn

{
    if (!_cancelBtn) {
        _cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        [_cancelBtn setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
        [_cancelBtn addTarget:self action:@selector(cancelPhoto) forControlEvents:UIControlEventTouchUpInside];
        _cancelBtn.titleLabel.font = [UIFont systemFontOfSize:18];
        [self.view addSubview:_cancelBtn];
        [_cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(15);
            make.bottom.equalTo(self.view.mas_top).equalTo(60);
        }];
    }
    return _cancelBtn;
 
}
- (UIButton *)cameraBtn {
    
    if (!_cameraBtn)
    {
        _cameraBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        NSBundle *bundel = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"YuanXinCamera" ofType:@"bundle"]];
        NSString *path = [bundel pathForResource:@"changeCamer" ofType:@"png"];
        [_cameraBtn setImage:[UIImage imageWithContentsOfFile:path] forState:UIControlStateNormal];
        _cameraBtn.clipsToBounds = YES;
        [self.view addSubview:_cameraBtn];
        [_cameraBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(-10);
            make.bottom.equalTo(self.cancelBtn.mas_bottom).equalTo(-5);
            make.size.equalTo(CGSizeMake(30, 30));
        }];
        
        [_cameraBtn addTarget:self action:@selector(changeCamera:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _cameraBtn;
}

- (UIButton *)flashBtn
{
    if (!_flashBtn)
        
    {
        _flashBtn = [UIButton buttonWithType:UIButtonTypeCustom];
       
        NSBundle *bundel = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"YuanXinCamera" ofType:@"bundle"]];
        NSString *pathSelect = [bundel pathForResource:@"flash_close_pic" ofType:@"png"];
        NSString *pathNorm = [bundel pathForResource:@"flash_open_pic" ofType:@"png"];

         [_flashBtn setImage:[UIImage imageWithContentsOfFile:pathNorm] forState:UIControlStateNormal];
     
        [_flashBtn setImage:[UIImage imageWithContentsOfFile:pathSelect
                             
                             ] forState:UIControlStateSelected];
        _flashBtn.clipsToBounds = YES;
        [_flashBtn addTarget:self action:@selector(changeFlashModel:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    
    return _flashBtn;
}
- (BOOL)allIsEmpty:(NSString *) str;
{
    
    if (!str) {
        return true;
    } else {
        
        NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
        
        NSString *trimedString = [str stringByTrimmingCharactersInSet:set];
        
        if ([trimedString length] == 0) {
            return true;
        } else {
            return false;
        }
    }
}

@end
